const router = require('koa-router')();
let config = require('../config.js').wx;
let sha1 = require('sha1');
router.prefix('/wx');

router.get('/', async (ctx, next) => {
  try {
    let token = config.token;
    let {signature, timestamp, nonce, echostr} = ctx.query;
    let arr = [token, timestamp, nonce];
    let str = sha1(arr.sort().join(''));
    if (str === signature) {
      ctx.body = echostr + '';
      return true;
    } else {
      ctx.body = '出错了';
      return false;
    }
  } catch (err) {
    throw err;
  }
});

router.get('/signature', async (ctx, next) => {
  let url = decodeURIComponent(ctx.query.targetUrl);
  let noncestr = Math.random().toString(36).substr(2, 15);
  let jsapiTicket = ctx.ticket;
  let timestamp = parseInt(Date.now() / 1000);
  let str = ['noncestr=' + noncestr, 'jsapi_ticket=' + jsapiTicket, 'timestamp=' + timestamp, 'url=' + url].sort().join('&');
  console.log('111111:', str);
  let signature = sha1(str);
  let obj = {
    appId: config.appID,
    timestamp,
    nonceStr: noncestr,
    signature
  };
  ctx.success(obj);
});
module.exports = router;
